const fs = require("fs");
const sqlite3 = require("sqlite3").verbose();
const DB = {};

DB.SqliteDB = class {
  constructor(file) {
    if (!file) {
      file = "./db/default.db";
    }
    DB.db = new sqlite3.Database(file);
    DB.exist = fs.existsSync(file);
    if (!DB.exist) {
      console.log("Creating db file!");
      fs.openSync(file, "w");
    }
  }
  createTable(sql) {
    return new Promise((resolve, reject) => {
      DB.db.serialize(function () {
        DB.db.run(sql, function (err) {
          if (null != err) {
            DB.printErrorInfo(err);
            reject(err);
            return;
          }
          resolve();
        });
      });
    });
  }
  /// tilesData format; [[level, column, row, content], [level, column, row, content]]
  insertData(sql, objects) {
    DB.db.serialize(function () {
      const stmt = DB.db.prepare(sql);
      for (let i = 0; i < objects.length; ++i) {
        stmt.run(objects[i]);
      }
      stmt.finalize();
    });
  }
  queryData(sql) {
    return new Promise((resolve, reject) => {
      DB.db.all(sql, function (err, rows) {
        if (null != err) {
          DB.printErrorInfo(err);
          resolve(false);
          return;
        }

        /// deal query data.
        resolve(rows);
      });
    });
  }
  executeSql(sql) {
    return new Promise((resolve, reject) => {
      DB.db.run(sql, function (err) {
        if (null != err) {
          DB.printErrorInfo(err);
          reject(err);
        }
      });
    });
  }
  close() {
    DB.db.close();
  }
};

DB.printErrorInfo = function (err) {
  console.log("Error Message:" + err.message);
};

/// export SqliteDB.
exports.SqliteDB = DB.SqliteDB;
